#include "net.hpp"
#include "dispatcher.hpp"
#include <thread>

void OnMessage(const MyRpc::BaseConnection::ptr& conn, const MyRpc::RpcResponse::ptr& msg)
{
    // 客户端收到消息之后的回调函数
    LOG(DEBUGLEVEL, "收到消息!");
    std::string body;
    // 把收到的数据放到body中
    bool flag = msg->serialize(body);
    if(flag == false)
    {
        LOG(DEBUGLEVEL, "消息序列化失败!");
        return;
    }
    std::cout << body << std::endl;
}

int main()
{
    MyRpc::BaseClient::ptr client = MyRpc::ClientFactory::create("127.0.0.1", 9090);
    client->setMessageCallBack(std::bind(&MyRpc::Dispatcher::OnMessage, MyRpc::disp.get(), std::placeholders::_1, std::placeholders::_2));

    MyRpc::disp->Register<MyRpc::RpcResponse>(MyRpc::MType::RSP_RPC, OnMessage);
    // 客户端连接服务端
    client->connect();
    // 创建请求类对象
    MyRpc::RpcRequest::ptr req = MyRpc::MessageFactory::create<MyRpc::RpcRequest>();
    // 设置请求数据
    req->setId(MyRpc::UUID::uuid());
    req->setMethod("Add");
    req->setMType(MyRpc::MType::REQ_RPC);
    Json::Value data;
    data["num1"] = 11;
    data["num2"] = 22;
    req->setParameters(data);
    // 发送请求给服务端
    client->send(req);
    // 等待5秒之后再关闭连接
    std::this_thread::sleep_for(std::chrono::seconds(5));
    // 关闭连接
    client->shutdown();
    return 0;
}

// int main1()
// {
//     MyRpc::BaseClient::ptr client = MyRpc::ClientFactory::create("127.0.0.1", 9090);
//     client->setMessageCallBack(OnMessage);
//     // 客户端连接服务端
//     client->connect();
//     // 创建请求类对象
//     MyRpc::RpcRequest::ptr req = MyRpc::MessageFactory::create<MyRpc::RpcRequest>();
//     // 设置请求数据
//     req->setId(MyRpc::UUID::uuid());
//     req->setMethod("Add");
//     req->setMType(MyRpc::MType::REQ_RPC);
//     Json::Value data;
//     data["num1"] = 11;
//     data["num2"] = 22;
//     req->setParameters(data);
//     // 发送请求给服务端
//     client->send(req);
//     // 等待5秒之后再关闭连接
//     std::this_thread::sleep_for(std::chrono::seconds(5));
//     // 关闭连接
//     client->shutdown();
//     return 0;
// }